<?php

namespace App\Service\ChatGroup;

use App\Enums\OpenShop\InvestmentPromotion\MainProcessEnum;
use App\Library\Lock\NxLock;
use App\Library\Rms\RmsShopApi;
use App\Library\Rms\RmsUserApi;
use App\Models\ChatGroup\ChatGroupHistoryModel;
use App\Models\ChatGroup\ChatGroupModel;
use App\Models\ChatGroup\ChatGroupSessionModel;
use App\Models\ChatGroup\ChatGroupUserModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Service\BaseService;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class ChatGroupMemberService extends BaseService
{
    /**
     * @throws GuzzleException
     */
    public static function list(int $shopId, int $groupId, int $userId): array
    {
//        // 获得老板的名称
//        $mainProcessModel = OpenShopMainProcessModel::query()
//            ->where('shopId', $shopId)
//            ->where('childLocationOrder', MainProcessEnum::CHILD_ORDER_0)
//            ->orderByDesc('id')
//            ->with(['userIdentityCardRel'])
//            ->first();

        $kuafuTeamList     = [];  // 夸父团队
        $existStaffUserIds = [];  // 已入群店员
        $memberCount       = 0;   // 在群人数
        $bossUid           = 0;   // 老板ID
        $tagList           = [];

        // 获得已有的成员列表
        ChatGroupUserModel::query()
            ->where('groupId', $groupId)
            ->where('shopId', $shopId)
            ->get()
            ->each(function (ChatGroupUserModel $chatGroupUserModel) use (&$bossUid, &$kuafuTeamList, &$existStaffUserIds, &$memberCount, &$tagList){
                $memberCount++;
                $tagList[$chatGroupUserModel->userId] = $chatGroupUserModel->tagText;
                // 夸父团队列表
                if ($chatGroupUserModel->role == ChatGroupUserModel::ROLE_KF) {
                    $kuafuTeamList[] = [
                        'name'    => $chatGroupUserModel->alias,
                        'role'    => $chatGroupUserModel->role,
                        'tagText' => $chatGroupUserModel->tagText,
                        'avatar'  => $chatGroupUserModel->avatar ? picturePath($chatGroupUserModel->avatar) : RmsUserApi::USER_DEFAULT_AVATAR_APP,
                        'roleStr' => ChatGroupUserModel::ROLE_MAPPING[$chatGroupUserModel->role] ?? '',
                        'userId'  => $chatGroupUserModel->userId,
                    ];
                }

                // 获得老板ID （权限判断）
                if ($chatGroupUserModel->role == ChatGroupUserModel::ROLE_BOSS) {
                    $bossUid = $chatGroupUserModel->userId;
                }

                // 存储在群员工ID
                if (in_array($chatGroupUserModel->role, [ChatGroupUserModel::ROLE_BOSS, ChatGroupUserModel::ROLE_EMPLOYEE])) {
                    $existStaffUserIds[] = $chatGroupUserModel->userId;
                }
            });

        // 获得门店下所有员工-只限商家APP的账户 如pos权限的人员无法登录app
        $staffList = (new RmsShopApi())->getShopStaffListByShopId($shopId, false, false, RmsShopApi::ROLE_BUSINESS_TYPE)['data']['list'] ?? [];

        // 获得员工ID于员工名称之前的映射关系
        $staffNameArr = collect($staffList)->pluck('username', 'id')->toArray();

        // 获得员工ID于员工头像之前的映射关系
        $staffAvatarArr = collect($staffList)->pluck('avatar', 'id')->toArray();

        // 获得员工列表
        $staffList = collect($staffList)->map(function ($staff) use ($staffNameArr, $staffAvatarArr, $bossUid, $existStaffUserIds, $userId, $tagList) {
            if (strlen($staffAvatarArr[$staff['id']])) {
                $avatar = picturePath($staffAvatarArr[$staff['id']]);
            } else {
                $avatar = RmsUserApi::USER_DEFAULT_AVATAR_APP;
            }

            return [
                'name'         => $staffNameArr[$staff['id']] ?? '店员',
                'userId'       => $staff['id'],
                'isPermission' => ($userId == $bossUid && $staff['id'] != $bossUid),
                'avatar'       => $avatar,
                'tagText'      => $tagList[$staff['id']] ?? '',
                'isExist'      => in_array($staff['id'], $existStaffUserIds),
            ];
        })->sortByDesc('sort')->values()->toArray();

        usort($staffList, function ($a, $b) use ($bossUid){
            if ($a['userId'] == $bossUid) {
                return -1;
            }
            if ($b['userId'] == $bossUid) {
                return 1;
            }

            // 如果isExist值不同，将isExist为true的排在前面
            if ($a['isExist'] != $b['isExist']) {
                return $b['isExist'] - $a['isExist'];
            }

            // 如果以上条件都不满足，就按照userId值进行排序
            return $a['userId'] - $b['userId'];
        });


        return [
            'count'       => $memberCount,
            'updateStaff' => $bossUid == $userId,
            'memberList'  => $kuafuTeamList,
            'staffList'   => $staffList
        ];
    }


    /**
     * 修改员工在群聊的状态
     * @param int $shopId
     * @param int $userId
     * @param bool $isExist
     * @param int $groupId
     * @return bool
     */
    public static function updateExist(int $shopId, int $userId, bool $isExist, int $groupId): bool
    {
        // 获得夸父团队列表
        $kfTeamUserIds = ChatGroupUserModel::query()
            ->where('groupId', $groupId)
            ->where('role', ChatGroupUserModel::ROLE_KF)
            ->where('shopId', $shopId)
            ->pluck('userId')
            ->toArray();

        if (in_array($userId, $kfTeamUserIds)) {
            self::throwErr('不能移除夸父团队的人员', 403);
        }

        // 通过UserId获得username
        $username = (new RmsUserApi())->getUserInfoByIds([$userId], ['username'])['data'][0]['username'] ?? '-';

        $content = '';
        switch ($isExist) {
            case ChatGroupUserModel::IS_EXIST_OFF:
                // 添加新纪录
                $groupUserModel = ChatGroupUserModel::query()->updateOrCreate([
                    'groupId'   => $groupId,
                    'shopId'    => $shopId,
                    'userId'    => $userId,
                    'role'      => ChatGroupUserModel::ROLE_EMPLOYEE,
                ]);
                $groupUserModel->save();
                $content = $username . '加入群聊';
                break;
            case ChatGroupUserModel::IS_EXIST_ON:
                // 修改之前的状态
                ChatGroupUserModel::query()
                    ->where('groupId', $groupId)
                    ->where('userId', $userId)
                    ->where('shopId', $shopId)
                    ->update([
                        'isDeleted' => 1
                    ]);
                $content = $username . '被移出了群聊';
                break;
            default:
        }

        // 发送消息
        (new ChatGroupStructService($groupId, $shopId))
            ->sendMsgStruct($userId, '', ChatGroupHistoryModel::TYPE_TIPS, $content, 0, 0,
                ChatGroupHistoryModel::IS_SEND_AI_NO)
            ->send();

        return true;
    }
}
